﻿using Microsoft.Extensions.Caching.Memory;
using SingleBlog.Core.Data;
using SingleBlog.Core.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SingleBlog.Core.Services
{
    /// <summary>
    /// 导航服务
    /// </summary>
    public class NavigationService
    {
        private readonly SingleBlogDbContext _context;
        private readonly IMemoryCache _cache;
        
        public NavigationService(SingleBlogDbContext context,IMemoryCache cache)
        {
            _context = context;
            _cache = cache;
        }

        /// <summary>
        /// 以异步的方式获取导航集合。
        /// </summary>
        /// <param name="enabledOnly">表示只获取字段 <c>Enabled = true</c> 的导航。 </param>
        /// <returns></returns>
        public Task<IEnumerable<Navigation>> GetNavigationsAsync(bool enabledOnly = true)
            =>
            Task.Run(() =>
            {
                IQueryable<Navigation> queryable = _context.Navigations;
                if (enabledOnly)
                {
                    queryable = queryable.Where(m => m.Enabled);
                }
                return queryable.OrderBy(m => m.OrderNo)
                .ThenBy(m => m.Id).ToList().AsEnumerable();
            });

        /// <summary>
        /// 以异步的方式获取指定id的导航。
        /// </summary>
        /// <param name="id">要获取的导航id。</param>
        /// <returns></returns>
        public Task<Navigation> GetNavigationAsync(int id)
            => _context.Navigations.FindAsync(id);

        /// <summary>
        /// 以异步的方式保存导航。Id == 0 是新增，否则是更新。
        /// </summary>
        /// <param name="item">要保存的导航实体。</param>
        /// <returns></returns>
        public async Task SaveNavigationAsync(Navigation item)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            if (item.Id == 0)
            {
                _context.Navigations.Add(item);
            }
            else
            {
                _context.Entry(item).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
            }
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 以异步的方式删除指定id的导航。
        /// </summary>
        /// <param name="id">要删除的导航id。</param>
        /// <returns></returns>
        public async Task DeleteNavigationAsync(int id)
        {
            var entityToRemove = await GetNavigationAsync(id);
            if (entityToRemove == null)
            {
                throw new NullReferenceException(Language.NavigationNotFound.StringFormat(id));
            }
            _context.Navigations.Remove(entityToRemove);
            await _context.SaveChangesAsync();
        }
    }
}
